package net.xdclass.func;

import com.alibaba.fastjson.JSONObject;
import net.xdclass.util.TimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;

public class UniqueVisitorFilterFunction extends RichFilterFunction<JSONObject> {

    private ValueState<String> lastVisitDataState = null;

    @Override
    public void open(Configuration parameters) throws Exception {
        ValueStateDescriptor<String> visitDataStateDes = new ValueStateDescriptor<>("visitDataState", String.class);
        //统计UV
        StateTtlConfig stateTtlConfig = StateTtlConfig.newBuilder(Time.days(1)).build();
        visitDataStateDes.enableTimeToLive(stateTtlConfig);

        lastVisitDataState = getRuntimeContext().getState(visitDataStateDes);
    }

    @Override
    public void close() throws Exception {
        super.close();
    }

    @Override
    public boolean filter(JSONObject jsonObj) throws Exception {
        //获取当前访问时间
        Long visitTime = jsonObj.getLong("visitTime");
        String udid = jsonObj.getString("udid");
        //当前访问时间
        String currentVisitDate = TimeUtil.format(visitTime);
        //获取上次的状态访问时间
        String lastVisitDate = lastVisitDataState.value();

        if (StringUtils.isNotBlank(lastVisitDate) && currentVisitDate.equalsIgnoreCase(lastVisitDate)) {
            System.out.println(udid + "已经在" + currentVisitDate + "时间访问过");
            return false;
        } else {
            System.out.println(udid + "在" + currentVisitDate + "时间初次访问");
            lastVisitDataState.update(currentVisitDate);
            return true;
        }
    }
}
